package com.cyan.note.service.impl;

import com.cyan.note.dto.admin.SystemStatsResponse;
import com.cyan.note.mapper.ShopMapper;
import com.cyan.note.mapper.UserMapper;
import com.cyan.note.service.SystemMonitorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;

import java.lang.management.ManagementFactory;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统监控服务实现类
 * 严格遵循数据隔离原则 - 只提供系统级统计数据
 * 
 * @author ZhangzhenYu
 * @since 2025-01-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SystemMonitorServiceImpl implements SystemMonitorService {

    private final ShopMapper shopMapper;
    private final UserMapper userMapper;

    @Override
    public SystemStatsResponse getSystemStats() {
        log.info("超级管理员获取系统整体统计数据");
        
        SystemStatsResponse response = new SystemStatsResponse();
        response.setStatsTime(LocalDateTime.now());
        response.setShopStats(getShopStats());
        response.setUserStats(getUserStats());
        response.setSystemStatus(getSystemStatus());
        
        return response;
    }

    @Override
    public SystemStatsResponse.ShopStats getShopStats() {
        log.info("获取店铺统计数据");
        
        SystemStatsResponse.ShopStats shopStats = new SystemStatsResponse.ShopStats();
        
        try {
            // 基础数量统计
            shopStats.setTotalCount(shopMapper.countTotal());
            shopStats.setActiveCount(shopMapper.countByStatus("active"));
            shopStats.setSuspendedCount(shopMapper.countByStatus("suspended"));
            shopStats.setClosedCount(shopMapper.countByStatus("closed"));
            
            // 状态分布
            Map<String, Long> statusDistribution = new HashMap<>();
            statusDistribution.put("active", shopStats.getActiveCount());
            statusDistribution.put("suspended", shopStats.getSuspendedCount());
            statusDistribution.put("closed", shopStats.getClosedCount());
            shopStats.setStatusDistribution(statusDistribution);
            
        } catch (Exception e) {
            log.error("获取店铺统计数据失败", e);
            // 出错时返回零值
            shopStats.setTotalCount(0L);
            shopStats.setActiveCount(0L);
            shopStats.setSuspendedCount(0L);
            shopStats.setClosedCount(0L);
            shopStats.setStatusDistribution(new HashMap<>());
        }
        
        return shopStats;
    }

    @Override
    public SystemStatsResponse.UserStats getUserStats() {
        log.info("获取用户统计数据");
        
        SystemStatsResponse.UserStats userStats = new SystemStatsResponse.UserStats();
        
        try {
            // 基础数量统计
            userStats.setTotalUsers(userMapper.countTotalUsers());
            userStats.setSuperAdminCount(userMapper.countUsersByRole("super_admin"));
            userStats.setManagerCount(userMapper.countUsersByRole("manager"));
            userStats.setWorkerCount(userMapper.countUsersByRole("worker"));
            
            // 状态统计
            userStats.setActiveUsers(userMapper.countUsersByStatus("active"));
            userStats.setInactiveUsers(userMapper.countUsersByStatus("inactive"));
            userStats.setLockedUsers(userMapper.countUsersByStatus("locked"));
            
            // 角色分布
            Map<String, Long> roleDistribution = new HashMap<>();
            roleDistribution.put("super_admin", userStats.getSuperAdminCount());
            roleDistribution.put("manager", userStats.getManagerCount());
            roleDistribution.put("worker", userStats.getWorkerCount());
            userStats.setRoleDistribution(roleDistribution);
            
            // 状态分布
            Map<String, Long> statusDistribution = new HashMap<>();
            statusDistribution.put("active", userStats.getActiveUsers());
            statusDistribution.put("inactive", userStats.getInactiveUsers());
            statusDistribution.put("locked", userStats.getLockedUsers());
            userStats.setStatusDistribution(statusDistribution);
            
        } catch (Exception e) {
            log.error("获取用户统计数据失败", e);
            // 出错时返回零值
            userStats.setTotalUsers(0L);
            userStats.setSuperAdminCount(0L);
            userStats.setManagerCount(0L);
            userStats.setWorkerCount(0L);
            userStats.setActiveUsers(0L);
            userStats.setInactiveUsers(0L);
            userStats.setLockedUsers(0L);
            userStats.setRoleDistribution(new HashMap<>());
            userStats.setStatusDistribution(new HashMap<>());
        }
        
        return userStats;
    }

    @Override
    public SystemStatsResponse.SystemStatus getSystemStatus() {
        log.info("获取系统运行状态");
        
        SystemStatsResponse.SystemStatus systemStatus = new SystemStatsResponse.SystemStatus();
        
        try {
            // 系统版本信息
            systemStatus.setVersion("1.0.0");
            
            // 系统启动时间和运行时长
            long startTimeMillis = ManagementFactory.getRuntimeMXBean().getStartTime();
            systemStatus.setStartTime(LocalDateTime.now().minusSeconds((System.currentTimeMillis() - startTimeMillis) / 1000));
            systemStatus.setUptime(ManagementFactory.getRuntimeMXBean().getUptime());
            
            // JVM信息
            systemStatus.setJvmInfo(getJvmInfo());
            
            // 数据库状态
            systemStatus.setDatabaseStatus(checkDatabaseStatus());
            
        } catch (Exception e) {
            log.error("获取系统状态失败", e);
            systemStatus.setVersion("unknown");
            systemStatus.setStartTime(LocalDateTime.now());
            systemStatus.setUptime(0L);
            systemStatus.setDatabaseStatus("error");
        }
        
        return systemStatus;
    }

    @Override
    public String checkDatabaseStatus() {
        try {
            // 尝试执行简单查询来检查数据库连接
            userMapper.countTotalUsers();
            return "connected";
        } catch (Exception e) {
            log.error("数据库连接检查失败", e);
            return "disconnected";
        }
    }

    /**
     * 获取JVM信息
     */
    private SystemStatsResponse.JvmInfo getJvmInfo() {
        SystemStatsResponse.JvmInfo jvmInfo = new SystemStatsResponse.JvmInfo();
        
        try {
            Runtime runtime = Runtime.getRuntime();
            
            // Java版本
            jvmInfo.setJavaVersion(System.getProperty("java.version"));
            jvmInfo.setJvmName(System.getProperty("java.vm.name"));
            
            // 内存信息（转换为MB）
            long maxMemory = runtime.maxMemory() / 1024 / 1024;
            long totalMemory = runtime.totalMemory() / 1024 / 1024;
            long freeMemory = runtime.freeMemory() / 1024 / 1024;
            long usedMemory = totalMemory - freeMemory;
            
            jvmInfo.setMaxMemory(maxMemory);
            jvmInfo.setTotalMemory(totalMemory);
            jvmInfo.setFreeMemory(freeMemory);
            jvmInfo.setUsedMemory(usedMemory);
            
            // 内存使用率
            double memoryUsage = maxMemory > 0 ? (double) usedMemory / maxMemory * 100 : 0;
            jvmInfo.setMemoryUsage(Math.round(memoryUsage * 100.0) / 100.0);
            
        } catch (Exception e) {
            log.error("获取JVM信息失败", e);
            jvmInfo.setJavaVersion("unknown");
            jvmInfo.setJvmName("unknown");
            jvmInfo.setMaxMemory(0L);
            jvmInfo.setTotalMemory(0L);
            jvmInfo.setFreeMemory(0L);
            jvmInfo.setUsedMemory(0L);
            jvmInfo.setMemoryUsage(0.0);
        }
        
        return jvmInfo;
    }
}